<template>
  <v-form ref="formRef">
    <v-container max-width="96%">
      <v-row class="mt-1">
        <v-col
            cols="12"
            md="6"
        >
          <v-textarea
              prepend-icon="mdi-import"
              label="整理目录"
              hint="需要整理的文件或目录，可多个，使用换行隔开。"
              :placeholder="'/data/music1\n/data/music2\n/data/music3'"
              v-model="form.inputSrc"
              variant="outlined"
              clearable
              auto-grow
              :rules="[v => !!v || '整理目录不能为空！']"
              required
          ></v-textarea>
        </v-col>
        <v-col
            cols="12"
            md="6"
        >
          <v-text-field
              prepend-icon="mdi-export"
              v-model="form.outputSrc"
              label="输出目录"
              variant="outlined"
              placeholder="/music"
              hint="整理后文件输出目录，不填写默认在第一个整理目录中生成一个music-organization-output目录；在整理文件时也会忽略music-organization-output文件目录。"
          ></v-text-field>
        </v-col>
        <v-col
            cols="12"
            md="6"
        >
          <v-select
              v-model="form.type"
              prepend-icon="mdi-link"
              :items="[{label: '复制', value: 'copy'},{label: '移动', value: 'move'},{label: '硬链接', value: 'hardLink'},{label: '软链接', value: 'softLink'}]"
              item-title="label"
              item-value="value"
              label="整理方式"
              variant="outlined"
              placeholder="复制"
              hint="复制、移动、移动、硬链接、软连接"
              required
              :rules="[v => !!v || '整理方式不能为空！']"
          ></v-select>
        </v-col>
        <v-col
            cols="12"
            md="6"
        >
          <v-select
              v-model="form.existType"
              prepend-icon="mdi-file-document-check-outline"
              :items="[{value: 'cover', label: '覆盖'}, {label: '跳过', value: 'skip'}, {label: '留下较大的', value: 'leaveLarger'}, {label: '留下最新的', value: 'leaveLatest'}]"
              item-title="label"
              item-value="value"
              label="文件已存在时"
              variant="outlined"
              placeholder="复制"
              hint="覆盖、留下较大的、留下最新的"
              :rules="[v => !!v || '文件已存在时方式不能为空！']"
              required
          ></v-select>
        </v-col>
        <v-col cols="12" md="12">
          <v-textarea
              prepend-icon="mdi-view-dashboard-outline"
              v-model="form.orgStruct"
              label="目录结构"
              variant="outlined"
              :placeholder="
              '不输入默认使用/{ARTIST}/{ALBUM}/{TITLE}-{ARTIST}.{SUFFIX}\n' +
              '使用默认时：Love Story-Taylor Swift.flac歌曲的目录结构：/Taylor Swift/Fearless/Love Story-Taylor Swift.flac\n' +
              '/霉霉/{YEAR}/{FILE_NAME}.{SUFFIX}\n' +
              'Love Story-Taylor Swift.flac歌曲的目录结构：/霉霉/2008/Love Story-Taylor Swift.flac'"
              hint="专辑：ALBUM；艺术家：ARTIST；标题：TITLE；年份：YEAR；专辑艺术家：ALBUM_ARTIST；源文件名称：FILE_NAME；后缀：SUFFIX；会根据指定结构在输出目录创建文件夹及自动重命名文件。"
          ></v-textarea>
        </v-col>
        <v-col :cols="5"></v-col>
        <v-col :cols="2">
          <v-btn @click="submit" class="align-center mr-4">提 交</v-btn>
          <v-dialog max-width="80%" v-model="logDialog">
            <template v-slot:activator="{ props: activatorProps }">
              <v-btn
                  v-bind="activatorProps"
                  class="align-center"
                  ref="logDialogBtn"
              >日 志</v-btn>
            </template>

            <template v-slot:default="{ isActive }">
              <v-card title="日志" id="log-textarea-card">
                <v-card-text>
                  <v-textarea
                      v-model="log"
                      variant="outlined"
                      clearable
                      auto-grow
                      readonly
                      rows="15"
                      required
                      color="red"
                      bg-color="rgb(46,52,54)"
                  ></v-textarea>
                </v-card-text>

                <v-card-actions>
                  <v-spacer></v-spacer>
                  <v-btn
                      text="关 闭"
                      @click="isActive.value = false"
                  ></v-btn>
                </v-card-actions>
              </v-card>
            </template>
          </v-dialog>
        </v-col>
        <v-col :cols="5"></v-col>
      </v-row>
    </v-container>
  </v-form>
</template>

<script setup>
import {nextTick, onUnmounted, ref} from "vue";
import {toast} from "vue3-toastify";
import {latestMusicOrganization, musicOrganizationSubmit} from "../api/MusicOrganizationApi.js";
import {getESS} from "../util/EESUtil.js";
import {closeSse} from "../api/SSEApi.js";

const form = ref({
  id: null,
  inputSrc: null,
  outputSrc: null,
  type: 'copy',
  existType: 'cover',
  orgStruct: null
});
const uid = ref(null);

const getLatestMusicOrganization = () => {
  latestMusicOrganization().then(res => {
    if (res.code === 200) {
      if (res.data) {
        form.value = res.data;
        form.value.type = form.value.type || 'copy';
        form.value.existType = form.value.existType || 'cover';
        uid.value = `music_organization_${form.value.id}`;
        connEventSource(uid.value);
      }
    } else {
      toast.error(res.msg);
    }
  });
}

getLatestMusicOrganization();

const log = ref('');
const logDialog = ref(false);
const eventSource = ref(null);
const connEventSource = (uid) => {
  eventSource.value = getESS(uid, (e) => {
    const msg = e.data;
    log.value += msg + '\n';
    nextTick(() => {
      const textarea = document.getElementById('log-textarea-card');
      textarea.scrollTop = textarea.scrollHeight;
    })
  })
};

onUnmounted(() => {
  if (eventSource.value) {
    closeSse(uid.value).then(res => {
      eventSource.value.close();
      eventSource.value = null;
    })
  }
})

const formRef = ref (null);
const submit = async () => {
  const { valid } = await formRef.value.validate();
  if (!valid) return;
  logDialog.value = true;
  log.value = '';
  musicOrganizationSubmit(form.value).then(res => {
    if (res.code === 200) {
      form.value = res.data;
    } else {
      toast.error(res.msg);
    }
  })
};

</script>

<style scoped>

</style>